<?php

class ConsultaController extends Controller {

    public $layout = '//layouts/column1';
    
    private $_modelAlocacao;

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'sala' and 'ambientesDinamicos' actions
                'actions' => array('sala', 'ambientesDinamicos'),
                'users' => array('*'),
            ),
            array('allow', // allow all users to perform 'sala' and 'ambientesDinamicos' actions
                'actions' => array('create', 'view'),
                'users' => array('@'),
            )
        );
    }

    public function actionAmbientesDinamicos() {
        $data = Ambiente::model()->findAll('ID_PREDIO=:ID_PREDIO', array(':ID_PREDIO' => (int) $_POST['ID_PREDIO']));

        $data = CHtml::listData($data, 'ID_AMBIENTE', 'TX_NOME');
        foreach ($data as $value => $name) {
            echo CHtml::tag('option', array('value' => $value), CHtml::encode($name), true);
        }
    }

    public function actionSala() {
        $modelConsulta = new ConsultaSala();
        $modelAlocacao = new Alocacao();
        $modelAmbiente = new Ambiente();
        $modelAmbienteRecurso = new Ambiente_Recurso();
        $modelResult = null;
        $consultar = FALSE;
        $dt = new DateTime('now');

        if (isset($_POST['ConsultaSala'])) {
            if (isset($_POST['ID_PREDIO']) && $_POST['ID_PREDIO'] != -1) {
                $modelConsulta->ID_AMBIENTE = $_POST['ConsultaSala']['ID_AMBIENTE'];
                $dt = $_POST['ConsultaSala']['DT_DIA'] == null ? date('d/m/Y', $dt->getTimestamp()) : $_POST['ConsultaSala']['DT_DIA'];
                $modelConsulta->DT_DIA = $dt;
                $modelConsulta->ID_PREDIO = $_POST['ID_PREDIO'];
                $consultar = TRUE;
            }
        } else if (isset($_GET['a']) && isset($_GET['b'])) {
            $modelConsulta->ID_AMBIENTE = $_GET['b'];
            $modelConsulta->DT_DIA = isset($_GET['c']) ? $_GET['c'] : date('d/m/Y', $dt->getTimestamp());
            $modelConsulta->ID_PREDIO = $_GET['a'];
            $consultar = TRUE;
        }
        if ($consultar === TRUE) {
            $dts = MethodUtils::getDtIniDtFim($modelConsulta->DT_DIA);
            $modelConsulta->dtIni = $dts[0];
            $modelConsulta->dtFim = $dts[1];
            $modelResult = $modelAlocacao->findAll(
                    'ID_AMBIENTE =:ID_AMBIENTE AND DT_DIA >= :DT_INI AND DT_DIA <= :DT_FIM', array(
                ':ID_AMBIENTE' => $modelConsulta->ID_AMBIENTE,
                ':DT_INI' => $modelConsulta->dtIni,
                ':DT_FIM' => $modelConsulta->dtFim
                    )
            );
            $modelAmbiente = $modelAmbiente->findByPk($modelConsulta->ID_AMBIENTE);
            $modelAmbienteRecurso->ID_AMBIENTE = $modelConsulta->ID_AMBIENTE;
        }
        if (isset($_POST['Alocacao_selected']) && isset($_POST['ID_AMBIENTE'])) {
            $model = new Alocacao;
            $ini = 1000000;
            $fim = 0;
            foreach ($_POST['Alocacao_selected'] as $value) {
                $args = explode('.', $value);
                $ini = min(array($ini, intval($args[1])));
                $fim = max(array($fim, intval($args[2])));
                $model->DT_DIA = $args[0];
            }
            $model->HR_INI = $ini;
            $model->HR_FIM = $fim;
            $this->redirect(
                    array(
                        'create',
                        'id' => $_POST['ID_AMBIENTE'],
                        'dia' => $model->DT_DIA,
                        'ini' => $model->HR_INI,
                        'fim' => $model->HR_FIM
                    )
            );
        } else {

            $this->render('sala', array(
                'modelC' => $modelConsulta,
                'modelA' => $modelAlocacao,
                'modelAm' => $modelAmbiente,
                'modelR' => $modelResult,
                'modelAR' => $modelAmbienteRecurso,
            ));
        }
    }

    public function actionCreate() {
        $model = new Alocacao;
        $modelAmbienteUso = new Ambiente_Uso;
        $modelUsuario = new Usuario();
        $modelAmbiente = new Ambiente();
        $modelPredio = new Predio();

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Alocacao'])) {
            $model->attributes = $_POST['Alocacao'];
            $model->HR_INI = intval(str_replace(':', '', $model->HR_INI));
            $model->HR_FIM = intval(str_replace(':', '', $model->HR_FIM));
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->ID_ALOCACAO));
        }else if (isset($_GET['id']) && isset($_GET['dia']) && isset($_GET['ini']) && isset($_GET['fim'])) {
            $modelAmbiente = $modelAmbiente->findByPk($_GET['id']);
            $modelPredio = $modelPredio->findByPk($modelAmbiente->ID_PREDIO);
            $model->DT_DIA = $_GET['dia'];
            $model->HR_INI = MethodUtils::getTimeFromInt($_GET['ini']);
            $model->HR_FIM = MethodUtils::getTimeFromInt($_GET['fim']);
        }

        $this->render('create', array(
            'model' => $model,
            'modelAU' => $modelAmbienteUso,
            'modelU' => $modelUsuario,
            'modelA' => $modelAmbiente,
            'modelP' => $modelPredio
        ));
    }
    
    public function actionView() {
        $this->render('view', array(
            'model' => $this->loadModelAlocacao(),
        ));
    }
    
    public function loadModelAlocacao() {
        if ($this->_modelAlocacao === null) {
            if (isset($_GET['id']))
                $this->_modelAlocacao = Alocacao::model()->findbyPk($_GET['id']);
            if ($this->_modelAlocacao === null)
                throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $this->_modelAlocacao;
    }

}

?>
